import java.util.ArrayList;

public class GeneralControlSolver {
	private ArrayList<String[][]> resultTables;
	int[][] table;
	int[][] output;

	public GeneralControlSolver(int[][] table, int[][] output)
	{
		this.table = table;
		this.output = output;
	}

	public String[] solve(int finalState)
	{
		TreeBuilder solver = new TreeBuilder(table, output);
		ArrayList<String> termSeq = solver.solveTerminal();
		ArrayList<String[][]> termTables = solver.getResultTable();

		ArrayList<String> generalSeq = new ArrayList<String>(termSeq.size());
		resultTables = new ArrayList<String[][]>(termSeq.size());

		for (int i = 0; i < termSeq.size(); i++)
		{
			// will check each sequence table 
			String[][] termTable = termTables.get(i);
			String[][] table = new String[termTable.length][4];
			
			// will try to get from each terminal state to the desired final state
			boolean solved = true;
			for (int j = 0; j < termTable.length; j++)
			{
				table[j][0] = termTable[j][0];
				table[j][1] = termTable[j][1];
				int initState = Integer.parseInt(termTable[j][0]);
				ArrayList<String> seq = solver.solveSimpleControl(initState,
						finalState);
				if (seq.size() == 0)
				{
					solved = false;
					break;
				} else
				{
					table[j][2] = seq.toString();
					table[j][3] = ""+finalState;
				}
			}
			// all output sequences can be redirected to the final state
			if (solved)
			{
				generalSeq.add(termSeq.get(i));
				resultTables.add(table);
			}
		}

		String[] sequences = new String[generalSeq.size()];
		generalSeq.toArray(sequences);

		return sequences;
	}

	public ArrayList<String[][]> getTables()
	{
		return resultTables;
	}
}
